package com.fbli.scoket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/***
 * 客户端，发送“hello,server”给服务端
 */
public class SocketTCP01Client {
    public static void main(String[] args) throws IOException {
        //1.连接服务端（ip,端口）
        //如果连接成功返回Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("socket返回=" + socket);
        //2.连接上后，生成socket，通过
        //通过socket.getOutputStream()
        //得到和socket对象关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();
        //3.通过输出流，写入数据到数据通道
        outputStream.write("hello,server".getBytes());
        //结束写入标记
        socket.shutdownOutput();
        //
        InputStream inputStream = socket.getInputStream();
        //4.io读取
        byte[] buf=new byte[1024];
        int readLen=0;
        while ((readLen=inputStream.read(buf))!=-1){
            System.out.println(new String(buf,0,readLen));//根据读取到的长度，显示内容。
        }
        //关闭输出流，socket
        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端退出。。。");
    }

}
